package com.wasp.collector.service.akka;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wasp.collector.content.Content;
import com.wasp.collector.data.RequestContext;
import com.wasp.collector.data.TimeInterval;
import com.wasp.collector.service.CollectorHelper;
import com.wasp.collector.service.HttpClientExecutor;

import akka.actor.AbstractActor;
import akka.japi.pf.ReceiveBuilder;
import scala.PartialFunction;
import scala.runtime.BoxedUnit;

public class CollectWorker extends AbstractActor {
	private static final Logger log = LoggerFactory.getLogger(CollectWorker.class);

	private int interval = 0;
	private boolean isStop = false;

	@Override
	public PartialFunction<Object, BoxedUnit> receive() {
		return ReceiveBuilder.match(TimeInterval.class, tv -> {
			interval = tv.getInterval();
			isStop = tv.isStop();
		}).match(HttpClientActorContext.class, context -> {
			collectData(context);
		}).build();
	}

	private void stopSelf() {
		getContext().stop(self());
	}
	private RequestContext buildRequestContext(RequestContext c,
			String url){
		RequestContext context = RequestContext.cloneRequest(c);
		context.setUrl(url);
		return context;
	}

	private void collectData(HttpClientActorContext context) {
		boolean isNeedReturn = false;
		// 判断是否停止
		if (isStop) {
			stopSelf();
			return;
		}
		ActorResult result = new ActorResult();
		result.setExecTime(new Date());
		result.setrContext(context.getContext());
		try {
			isNeedReturn = true;
			// 如果interval被设置值，则延迟
			if (interval > 0) {
				TimeUnit.MILLISECONDS.sleep(interval);
			}
			HttpClientExecutor hExec = new HttpClientExecutor(context.getWrapper(),context.getContext());
			Content content = hExec.exec();
			List<String> nexts = CollectorHelper.getHandler(context.getWrapper()).handleAndGenNext(content);
			
			RequestContext rc = context.getContext();
			if (nexts != null) {
				List<RequestContext> rcxs = nexts.stream().collect(() -> new ArrayList<RequestContext>(),
						(tmp, item) -> tmp.add(buildRequestContext(rc, item)), (list1, list2) -> list1.addAll(list2));

				result.setNexts(rcxs);

			}
			if (isNeedReturn) {
				sender().tell(result, self());
			}
		} catch (Exception ex) {
			log.error("e",ex);
			result.setException(ex);

			if (isNeedReturn) {
				sender().tell(result, self());
			}
		} finally {
			if (isNeedReturn) {
				//stopSelf();
			}
		}
	}
}
